package com.xsomnus.open.im.auth;

import com.xsomnus.open.im.protocol.Packet;
import com.xsomnus.open.im.protocol.codec.PacketCodec;
import com.xsomnus.open.im.protocol.request.LoginRequestPacket;
import com.xsomnus.open.im.protocol.response.LoginResponsePacket;
import com.xsomnus.open.im.protocol.response.MessageResponsePacket;
import com.xsomnus.open.im.util.LoginUtils;
import com.xsomnus.open.im.util.PrintUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.UUID;

/**
 * @author @xsomnus666_xiawenye★
 * @since 2019/4/24 0024 18:34
 * 当你发现自己的才华撑不起野心时，就请安静下来学习吧
 */
public class AuthClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        PrintUtils.print("客户端开始登陆");

        // 构建登陆对象
        LoginRequestPacket loginRequestPacket = new LoginRequestPacket();
        loginRequestPacket.setUserId(UUID.randomUUID().toString());
        loginRequestPacket.setUsername("xsomnus666");
        loginRequestPacket.setPassword("123456");
        // 编码
        ByteBuf buf = PacketCodec.INSTANCE.encode(ctx.alloc(), loginRequestPacket);
        // 写数据
        ctx.channel().writeAndFlush(buf);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        // 解码
        Packet packet = PacketCodec.INSTANCE.decode(byteBuf);

        if (packet instanceof LoginResponsePacket) {
            LoginResponsePacket loginResponsePacket = (LoginResponsePacket) packet;
            if (loginResponsePacket.isSuccess()) {
                LoginUtils.markAsLogin(ctx.channel());
                PrintUtils.print("客户端登陆成功!");
            } else {
                PrintUtils.print("客户端登陆失败, 原因是: " + loginResponsePacket.getReason());
            }
        } else if (packet instanceof MessageResponsePacket) {
            MessageResponsePacket messageResponsePacket = (MessageResponsePacket) packet;
            PrintUtils.print("收到服务端消息: " + messageResponsePacket.getMessage());
        }

    }
}
